package algorithm.array;

import java.util.*;

/**
 * 找出一个数组中出现次数最多的元素
 */
public class MajorityElement {

    public static void main(String[] args) {

        int [] nums = {2,2,1,1,1,2,2};
        System.out.println(majorityElement(nums));
    }

    public static int majorityElement(int[] nums) {

        Map<Integer, Integer> map = new HashMap();

        for (int i = 0; i < nums.length ; i++) {
            if (!map.containsKey(nums[i])){
                map.put(nums[i], 1);
            }else{
                map.put(nums[i], map.get(nums[i]) + 1);
            }
        }

        Collection<Integer> values = map.values();
        Object[] objects = values.toArray();
        Arrays.sort(objects);
        int maxValue = Integer.parseInt(objects[objects.length - 1].toString());

        //  154   359    146
        int key = 0;
        for (Map.Entry<Integer, Integer> entries : map.entrySet()){
            if (maxValue == entries.getValue()){
                key = entries.getKey();
            }
        }

        return key;
    }
}
